﻿using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
using System.Reflection;
using Nancy;

[assembly: OwinStartup(typeof(Wings.Web.Startup))]

namespace Wings.Web
{
    public class Startup
    {

        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息，请访问 http://go.microsoft.com/fwlink/?LinkID=316888
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //var json = config.Formatters.JsonFormatter;
            //json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            //var connectioninfo = ConnectionInfo.FromAppConfig("mongodb");

            var builder = new ContainerBuilder();                                    // Create the container builder.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());         // Register the Web API controllers.
            //builder.Register(c => new Logger()).As<ILogger>().InstancePerRequest();  // Register a logger service to be used by the controller and middleware.
            //builder.RegisterType<AuthenticationRepository>().As<IAuthenticationRepository>().WithParameter(new NamedParameter("connectionInfo", connectioninfo)).InstancePerRequest();
            builder.RegisterModule(new NhibernateModule());

            var container = builder.Build();

            var resolver = new AutofacWebApiDependencyResolver(container);           // Create an assign a dependency resolver for Web API to use.
            config.DependencyResolver = resolver;   // Configure Web API with the dependency resolver
            //app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(config);
            app.UseAutofacWebApi(config);  // Make sure the Autofac lifetime scope is passed to Web API.
            var bootstrapper = new MyAwesomeNancyBootstrapper(container);
			StaticConfiguration.DisableErrorTraces = false;
            app.UseNancy(options =>  options.Bootstrapper = bootstrapper);

            //var res = container.Resolve<Repostory.IBookRepostory>();

        }

    }
}
